def ckpt2txt(read_from_path,save_to_path):
    """功能：将ckpt写入txt文件（转为str后）；
    调用：
    FileNotFoundError: [Errno 2] No such file or directory: 'MEDsmall/checkpoint_best.pt'
    """
    import torch
    # read_from_path='temp.ckpt'
    # save_to_path='temp.txt'
    lz = torch.load(read_from_path)# 加载为dict 格式
    #pickle文件-转换写入txt文件
    txt_file = open(save_to_path, 'w', encoding='utf-8')
    fi = str(lz)  # 转换变量为str格式；TypeError: write() argument must be str, not list
    txt_file.write(fi)
    # 注意关闭文件
    txt_file.close()
    print(f"{save_to_path}:写入成功！")
# ckpt2txt("MEDsmall/checkpoint_best.pt","MEDsmall/checkpoint_best.txt")


def ckpt2txt_autoname(ckpt_path):
    """功能：将ckpt写入txt文件（转为str后）-自动改后缀名；
    适用：仅取键'model_state_dict'值；
    """
    import torch
    # ckpt_path = "MEDsmall/checkpoint_best.pt"
    # 加载ckpt文件
    checkpoint = torch.load(ckpt_path)
    # 获取ckpt文件中保存的模型参数
    model_state_dict = checkpoint['model_state_dict']
    # 生成输出文件名
    output_file_name = ckpt_path.replace('.pth', '.txt')
    # 将模型参数保存为txt文件
    with open(output_file_name, 'w') as f:
        for key in model_state_dict:
            f.write('{}\n{}\n'.format(key, model_state_dict[key]))
    print(f"{output_file_name}:写入成功！")
# ckpt2txt_autoname("MEDsmall/checkpoint_best.pt")
